import {
    Body,
    Controller,
    Delete,
    Get,
    Param,
    ParseIntPipe,
    Post,
    Put,
    Render,
    Request,
    Response,
} from '@nestjs/common';
import { PostsService } from './posts.service';
import { CreatePostsDto } from './posts.dto';
import { EntityManager, Transaction, TransactionManager } from 'typeorm';

@Controller('posts')
export class PostsController {
    // 使用方式需要使用@Inject的方式
    constructor (
      private readonly postsService: PostsService,
    ) { }

    @Get()
    @Render('posts/index')
    async index(@Request() req) {
        const list = await this.postsService.list()
        return { list }
    }

    @Get('add')
    @Render('posts/add')
    async addPage() {
        return { title:'新增',id:'',name:'',content:''}
    }

    @Get('edit')
    @Render('posts/add')
    async editPage(@Param('id', new ParseIntPipe()) id: number) {
        return { title:'编辑'}
    }

    @Post()
    @Transaction()
    async save(@Body() post:CreatePostsDto, @Response() res: { [key: string]: any },  @TransactionManager() manager: EntityManager,) {
        console.log(post);
        await this.postsService.create(post, manager)
        res.redirect('/posts')
    }

    @Delete()
    async del(@Body() post) {
        await this.postsService.delete(post.id)
    }f

    @Get(':ids')
    @Render('posts/detail')
    async detail( @Param('ids', new ParseIntPipe()) id:string) {
        const detail = await this.postsService.findById([id])
        console.log(detail);
        return detail
    }
}
